package site.teamo.biu.net.server.core.http_https_proxy;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import site.teamo.biu.net.common.exception.BiuNetBusinessException;
import site.teamo.biu.net.common.http_https_proxy.ConnectionState;
import site.teamo.biu.net.common.web.constant.ResponseCode;
import site.teamo.biu.net.common.web.mapper.SystemConfigMapper;
import site.teamo.biu.net.server.configuration.ServerConfiguration;
import site.teamo.biu.net.server.core.http_https_proxy.server.ProxyRequestListeningServer;
import site.teamo.biu.net.server.core.http_https_proxy.state.HttpHttpsProxyState;
import site.teamo.biu.tool.spring.listener.ApplicationReadyListener;

import java.util.Optional;

/**
 * @author: 爱做梦的锤子
 * @date: 2023/3/26 16:58
 */
@Service
public class HttpHttpsProxyService {

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Resource
    private ApplicationReadyListener applicationReadyListener;

    @PostConstruct
    public void init() {
        applicationReadyListener.addJob("Http&Https代理服务启动", this::restart);
    }


    private ConnectionHandler connectionHandler;

    private ProxyRequestListeningServer server;

    private TrafficStatistics trafficStatistics;

    /**
     * 启用代理服务
     */
    public synchronized void restart() {
        Optional.ofNullable(server).ifPresent(ProxyRequestListeningServer::close);
        Optional.ofNullable(connectionHandler).ifPresent(ConnectionHandler::close);
        this.trafficStatistics = ServerConfiguration.HTTP_HTTPS_PROXY_SERVICE_TRAFFIC_STATISTICS.getContent(systemConfigMapper, TrafficStatistics.class);
        this.connectionHandler = new ConnectionHandler(this.trafficStatistics);
        this.server = new ProxyRequestListeningServer(this.connectionHandler);
    }

    public synchronized void changePort(int port) {
        if (!NetUtil.isValidPort(port)) {
            throw new BiuNetBusinessException(ResponseCode.BUSINESS_ERROR, "不合法的端口");
        }
        int currentPort = Integer.parseInt(ServerConfiguration.HTTP_HTTPS_PROXY_SERVICE_LISTEN_PORT.getContent(systemConfigMapper));
        if (currentPort == port) {
            return;
        }
        ServerConfiguration.HTTP_HTTPS_PROXY_SERVICE_LISTEN_PORT.setContent(systemConfigMapper, String.valueOf(port));
        this.restart();
    }

    /**
     * 获取服务状态
     */
    public HttpHttpsProxyState state() {
        return null;
    }

    public ConnectionState proxyConnectionState() {
        return null;
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void saveTrafficStatistics() {
        ServerConfiguration.HTTP_HTTPS_PROXY_SERVICE_TRAFFIC_STATISTICS.setContent(systemConfigMapper, JSON.toJSONString(this.trafficStatistics));
    }
}
